package com.chenqi.myblog.controller.admin;

import com.chenqi.myblog.model.Blog;
import com.chenqi.myblog.model.Type;
import com.chenqi.myblog.model.User;
import com.chenqi.myblog.service.BlogService;
import com.chenqi.myblog.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.net.URLEncoder;
import java.util.List;

/**
 * @description: 分类管理控制器
 * @program: myblog
 * @author: ChenQi
 * @create: 2021-02-2021/2/2-09-50
 */
@Controller
@RequestMapping("/admin")
public class ATypeController {

    @Autowired
    private TypeService typeService;

    @Autowired
    private BlogService blogService;
    /**
     * 后台展示所有信息(不分页)
     * @param modelAndView
     * @return
     */
    @GetMapping("/type_list")
    public ModelAndView getTypes(ModelAndView modelAndView) {
        List<Type> types = typeService.findAllType();
        modelAndView.addObject("types", types);
        modelAndView.setViewName("admin/types");
        return modelAndView;
    }

    /**
     * 添加分类
     * @param name
     * @param modelAndView
     * @return
     */
    @PostMapping("/saveType")
    public ModelAndView saveType(@RequestParam("name") String name,ModelAndView modelAndView) {
        Type type = new Type();
        type.setName(name);
        typeService.save(type);
        modelAndView.setViewName("redirect:/admin/type_list");
        return modelAndView;
    }

    /**
     * 删除分类
     * @param id
     * @param modelAndView
     * @return
     */
    @GetMapping("/removeType")
    public ModelAndView removeType(@RequestParam("id") Integer id,ModelAndView modelAndView) {
        List<Blog> blogs = blogService.findByTypeId(id);
        if (blogs == null || blogs.size()==0) {
            typeService.remove(id);
            modelAndView.setViewName("redirect:/admin/type_list");
            return modelAndView;
        }
        modelAndView.setViewName("redirect:/admin/type_list?msg=you can not delete this type now,becaues have some blogs belong it.Please delete the blogs belong it first,then you can detele the type.");
        return modelAndView;
    }
}
